package solution._0050._0054;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chen_snow
 * Date: 2021/6/9 20:33
 * Description:
 */
public class Solution {

    public static void main(String[] args) {
        spiralOrder(new int[][]{{6, 9, 7}});
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<>();

        int index = (Math.min(matrix.length, matrix[0].length) + 1) / 2;

        for (int i = 0; i < index; i++) {
            add(matrix, i, matrix[0].length - i - 1, i, matrix.length - i - 1, result);
        }
        return result;
    }

    public static void add(int[][] matrix, int left, int right, int up, int down, List<Integer> result) {

        boolean isOneRow = up == down ? true : false;
        boolean isOneColumn = left == right ? true : false;
        for (int column = left; column <= right; column++) {
            result.add(matrix[up][column]);
        }

        if (!isOneRow) {
            for (int row = up + 1; row <= down; row++) {
                result.add(matrix[row][right]);
            }

            for (int column = right - 1; column >= left; column--) {
                result.add(matrix[down][column]);
            }
        }

        if (!isOneColumn) {
            for (int row = down - 1; row > up; row--) {
                result.add(matrix[row][left]);
            }
        }

    }

}
